import React from 'react';
import {Button, Table} from 'antd';
import {inject, observer} from 'mobx-react';
import {queryWeather} from '@/services';

import './index.scss';

//表格的列
const columns = [
  {
    title: '时间',
    dataIndex: 'date',
    key: 'date'
  },
  {
    title: '风力',
    dataIndex: 'fengli',
    key: 'fengli'
  },
  {
    title: '风向',
    dataIndex: 'fengxiang',
    key: 'fengxiang'
  },
  {
    title: '最高温',
    dataIndex: 'high',
    key: 'high'
  },
  {
    title: '最高温',
    dataIndex: 'low',
    key: 'low'
  },
  {
    title: '状况',
    dataIndex: 'type',
    key: 'type'
  }
];

/**
 * 订单页面
 * @inject    用来将Store添加到组件的属性中。参数一为Store的名称。
 * @observer  用来声明组件为mobx的观察者。当Store的可观察属性改变时，刷新页面。注意：先使用@inject，后使用@observer。
 */
@inject('store')
@observer
export default class Order extends React.Component {
  //构造函数
  constructor(props) {
    super(props);
    //使用state保存数据
    this.state = {};
  }

  //界面渲染函数
  render() {
    return (
      <div className="order">
        <div>
          <Button onClick={this.queryWeather}>查询天气</Button>
          {this.renderWeather()}
        </div>
        <div>
          <Button onClick={this.addData}>新增</Button>
          {this.renderList()}
        </div>
      </div>
    );
  }

  /**
   * 加载列表
   */
  renderList() {
    let {dataList} = this.props.store.order;
    return dataList.map((item, index) => {
      return (
        <div key={index}>
          <span>{item.title}</span>
          <Button onClick={() => this.deleteData(index)}>删除</Button>
        </div>
      );
    });
  }

  /**
   * 加载天气
   */
  renderWeather() {
    let {dataWeather} = this.state;

    return <Table dataSource={dataWeather} columns={columns} />;
  }

  addData = () => {
    let {dataListLength, addData} = this.props.store.order;
    let data = {title: `Ant Design Title ${dataListLength}`};
    addData(data);
  };

  deleteData = (index) => {
    this.props.store.order.deleteData(index);
  };

  queryWeather = () => {
    let param = {city: '北京'};
    let config = {typeResult: 3, isShowError: true, isCheckStatus: true};
    queryWeather(param, config)
      .then((r) => {
        console.log('weather', r);

        let dataWeather = r && r.forecast;
        dataWeather.forEach((item, key) => (item.key = key));
        this.setState({dataWeather});
      })
      .catch((e) => {
        console.error(typeof e, e);
      });
  };
}
